/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.bingoogolapple.qrcode.slice;

import com.bingoogolapple.qrcode.ResourceTable;
import com.bingoogolapple.qrcode.core.BarcodeType;
import com.bingoogolapple.qrcode.core.LogUtil;
import com.bingoogolapple.qrcode.core.QRCodeView;
import com.bingoogolapple.qrcode.core.TextUtils;

import com.bingoogolapple.qrcode.zxing.ZXingView;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.ComponentContainer;
import ohos.agp.components.Text;
import ohos.agp.window.dialog.ToastDialog;
import ohos.app.Context;
import ohos.eventhandler.EventHandler;
import ohos.eventhandler.EventRunner;
import ohos.vibrator.agent.VibratorAgent;

import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;


/**
 * zxing扫描页面
 */
public class ZxingTestScanAbilitySlice extends AbilitySlice implements Component.ClickedListener, QRCodeView.Delegate{

    private ZXingView mZXingView;
    private Text text2;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_zxingscan_layout);
        getWindow().setTransparent(true);
        mZXingView = (ZXingView) findComponentById(ResourceTable.Id_zxingview);
        mZXingView.setDelegate(this);
        text2 = (Text) findComponentById(ResourceTable.Id_text2);
        findComponentById(ResourceTable.Id_start_spot).setClickedListener(this);
        findComponentById(ResourceTable.Id_show_scan_rect).setClickedListener(this);
        findComponentById(ResourceTable.Id_hidden_scan_rect).setClickedListener(this);
        findComponentById(ResourceTable.Id_stop_spot).setClickedListener(this);

        findComponentById(ResourceTable.Id_decode_full_screen_area).setClickedListener(this);
        findComponentById(ResourceTable.Id_open_flashlight).setClickedListener(this);
        findComponentById(ResourceTable.Id_close_flashlight).setClickedListener(this);
        findComponentById(ResourceTable.Id_scan_one_dimension).setClickedListener(this);

        findComponentById(ResourceTable.Id_scan_two_dimension).setClickedListener(this);
        findComponentById(ResourceTable.Id_scan_qr_code).setClickedListener(this);
        findComponentById(ResourceTable.Id_scan_code128).setClickedListener(this);
        findComponentById(ResourceTable.Id_scan_ean13).setClickedListener(this);

        findComponentById(ResourceTable.Id_scan_high_frequency).setClickedListener(this);
        findComponentById(ResourceTable.Id_scan_all).setClickedListener(this);
        findComponentById(ResourceTable.Id_scan_custom).setClickedListener(this);
        findComponentById(ResourceTable.Id_choose_qrcde_from_gallery).setClickedListener(this);

    }




    @Override
    protected void onActive() {
        super.onActive();
        mZXingView.startSpotAndShowRect();
        mZXingView.setDelegate(this);
    }

    @Override
    protected void onInactive() {
        super.onInactive();
        mZXingView.onDestroy();
    }

    private void vibrate() {
        VibratorAgent vibratorAgent = new VibratorAgent();
        List<Integer> vids = vibratorAgent.getVibratorIdList();
        LogUtil.info("vibrate size:"+ vids.size());
        for(Integer position:vids) {
            LogUtil.info("vibrate id:" + vids);
            if(vibratorAgent.isSupport(position)) {
                vibratorAgent.startOnce(position, 200);
                break;
            }
        }
    }

    void setTitle(String title)
    {
        String res = "未识别";
        if(!TextUtils.isEmpty(title))
        {
            res  = title;
        }
        showTips(getContext(),res);


    }

    private void showTips(Context context, String message) {
        getUITaskDispatcher().asyncDispatch(() -> {
            text2.setText(message);
        });
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        mZXingView.startSpot(); // 开始识别
        if(TextUtils.isEmpty(result))
        {
            return;
        }
        LogUtil.error( "result:" + result);
        setTitle( result);
        vibrate();
    }

    @Override
    public void onCameraAmbientBrightnessChanged(boolean isDark) {
        // 这里是通过修改提示文案来展示环境是否过暗的状态，接入方也可以根据 isDark 的值来实现其他交互效果
        String tipText = mZXingView.getScanBoxView().getTipText();
        String ambientBrightnessTip = "\n环境过暗，请打开闪光灯";
        if (isDark) {
            if (!tipText.contains(ambientBrightnessTip)) {
                mZXingView.getScanBoxView().setTipText(tipText + ambientBrightnessTip);
            }
        } else {
            if (tipText.contains(ambientBrightnessTip)) {
                tipText = tipText.substring(0, tipText.indexOf(ambientBrightnessTip));
                mZXingView.getScanBoxView().setTipText(tipText);
            }
        }
    }


    @Override
    public void onScanQRCodeOpenCameraError() {
        LogUtil.info( "opencamera_error");
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()){
            case ResourceTable.Id_start_spot: // 此处修改为开始识别
                mZXingView.startSpotAndShowRect(); // 显示扫描框
                mZXingView.setDelegate(this);
                break;
            case ResourceTable.Id_stop_spot:
                mZXingView.stopCallBack(); // 停止识别
                break;
            case ResourceTable.Id_show_scan_rect:
                mZXingView.showScanRect(); // 显示扫描框
                break;
            case ResourceTable.Id_hidden_scan_rect:
                mZXingView.hiddenScanRect(); // 隐藏扫描框
                break;
            case ResourceTable.Id_decode_full_screen_area:
                mZXingView.getScanBoxView().setOnlyDecodeScanBoxArea(false); // 识别整个屏幕中的码
                break;
            case ResourceTable.Id_open_flashlight:
                mZXingView.openFlashlight(); // 打开闪光灯
                break;
            case ResourceTable.Id_close_flashlight:
                mZXingView.closeFlashlight(); // 关闭闪光灯
                break;
            case ResourceTable.Id_scan_one_dimension:
                mZXingView.changeToScanBarcodeStyle(); // 切换成扫描条码样式

                mZXingView.setType(BarcodeType.ONE_DIMENSION, null); // 只识别 CODE_128
                mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
                break;
            case ResourceTable.Id_scan_two_dimension:
                mZXingView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式

                mZXingView.setType(BarcodeType.TWO_DIMENSION, null); // 识别所有类型的码
                mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
                break;
            case ResourceTable.Id_scan_qr_code:
                mZXingView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式

                mZXingView.setType(BarcodeType.ONLY_QR_CODE, null); // 识别所有类型的码
                mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
                break;
            case ResourceTable.Id_scan_code128:
                mZXingView.changeToScanBarcodeStyle(); // 切换成扫描条码样式
                mZXingView.setType(BarcodeType.ONLY_CODE_128, null); // 只识别 CODE_128
                mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
                break;
            case ResourceTable.Id_scan_ean13:
                mZXingView.changeToScanBarcodeStyle(); // 切换成扫描条码样式
                mZXingView.setType(BarcodeType.ONLY_EAN_13, null); // 只识别 CODE_128
                mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
                break;
            case ResourceTable.Id_scan_high_frequency:
                mZXingView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式
                mZXingView.setType(BarcodeType.HIGH_FREQUENCY, null); // 只识别高频率格式，包括 QR_CODE、ISBN13、UPC_A、EAN_13、CODE_128
                mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
                break;
            case ResourceTable.Id_scan_all:
                mZXingView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式
                mZXingView.setType(BarcodeType.ALL, null); // 识别所有类型的码
                mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
                break;
            case ResourceTable.Id_scan_custom:
                scanCustomMethod();
                break;
            default:
                break;
        }
    }


    private void scanCustomMethod() {
        mZXingView.changeToScanQRCodeStyle(); // 切换成扫描二维码样式
        Map<DecodeHintType, Object> hintMap = new EnumMap<>(DecodeHintType.class);
        List<BarcodeFormat> formatList = new ArrayList<>();
        formatList.add(BarcodeFormat.QR_CODE);
        formatList.add(BarcodeFormat.UPC_A);
        formatList.add(BarcodeFormat.EAN_13);
        formatList.add(BarcodeFormat.CODE_128);
        hintMap.put(DecodeHintType.POSSIBLE_FORMATS, formatList); // 可能的编码格式
        hintMap.put(DecodeHintType.TRY_HARDER, Boolean.TRUE); // 花更多的时间用于寻找图上的编码，优化准确性，但不优化速度
        hintMap.put(DecodeHintType.CHARACTER_SET, "utf-8"); // 编码字符集
        mZXingView.setType(BarcodeType.CUSTOM, hintMap); // 自定义识别的类型

        mZXingView.startSpotAndShowRect(); // 显示扫描框，并开始识别
    }
}
